#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import win32api, win32con, win32gui
import uiautomation as automation
import os, sys, time, re, subprocess, argparse, json
from WorkflowScript.SendEmail import SendEmail

ToolPath = r'E:\09-工作流推包\打包工具\Mysoft.PackageApp.exe'
PackageRemark = 'Tips：更新前要先停工作流应用程序池，更新完成后再开启，请再下班时间更新！'
# PackageRemark='更新前先停工作流应用程序池，更新完成后再开启，请再下班时间更新'
User = 'wf'
PassWd = 'wf1qaz'


# 通过读MysoftVersion_WF.config文件获取版本号传入PackageVer,再拼接到PackageName
def GetWFVserion(BasePath):
    filepath = os.path.join(BasePath, 'src\MysoftVersion_WF.config')
    # filepath = unicode(filepath, 'utf-8')
    with open(filepath, 'r',encoding='utf8') as f:
        content = f.read()
        version = re.findall(r'<Version>(.+?)</Version>', content)[0]
        print ('%s工作流版本: %s' % (filepath, version))
    return version


def upgradeTools(ToolPath, CustomerName, ProductName, PackageName, PackageVer, FileFolder, PackageRemark, User, PassWd):
    # # 对变量进行转码，含有中文的输入需要转码后才能输入
    # CustomerName = str2unicode(Customer)
    # ProductName = str2unicode(Product)
    # PackageName = str2unicode(PackageName)
    # PackageVer = str2unicode(PackageVer)
    # FileFolder = str2unicode(FileFolder)
    # PackageRemark = str2unicode(PackageRemark)
    # 再重新打开退包工具
    win32api.ShellExecute(0, 'open', ToolPath, '', '', 1)
    UpgradeWindow = automation.WindowControl(searchDepth=1, RegexName='明源更新包上传工具', AutomationId='MainForm')
    if automation.WaitForExist(UpgradeWindow, 4):
        automation.Logger.WriteLine(u"明源更新包上传工具已打开")
    # 点击个性化radio
    PersonalButton = UpgradeWindow.RadioButtonControl(AutomationId='radbtnPersonal')
    PersonalButton.Click()
    # chose=1048576表示未选中，1048596表示选中，1048580不知道是啥
    chose = PersonalButton.AccessibleCurrentState()
    i = 0
    print(f"{str(chose)},点击个性化radio")
    while chose != 1048596:
        i = i+1
        PersonalButton.Click()
        chose = PersonalButton.AccessibleCurrentState()
        print(f"{str(chose)},第{str(i)}次重复点击radio")
        if i==5:
            break
    # 输入客户名称
    CustomerInput = UpgradeWindow.EditControl(AutomationId='1001')
    # python2中要使用Unicode, 模拟按键
    CustomerInput.SendKeys(CustomerName + '{ENTER}')
    # comCustomerInput.SendKeys(u'{Ctrl}{End}{Enter}下面开始演示{! 4}{ENTER}')
    # 点击产品下拉框
    ProductWin = UpgradeWindow.ComboBoxControl(AutomationId='comProduct')
    ProductWin.Click()
    # chose=1049600表示未点击成功，1049092表示点击成功
    chose = ProductWin.AccessibleCurrentState()
    i = 0
    while chose != 1049092:
        i = i+1
        ProductWin.Click()
        chose = ProductWin.AccessibleCurrentState()
        print(f"{str(chose)},第{str(i)}次重复点击产品下拉框")
        if i == 5:
            break
    # 选择产品
    ProductSelectWin = UpgradeWindow.ListItemControl(Name=ProductName)
    ProductSelectWin.Select()

    # 输入更新包名称
    PackageNameWin = UpgradeWindow.EditControl(AutomationId='txtPackageName')
    PackageNameWin.SetValue(PackageName)
    # 输入更新包版本
    PackageVerWin = UpgradeWindow.EditControl(AutomationId='txtPackageVer')
    PackageVerWin.SetValue(PackageVer)
    # 输入更新包目录
    FileFolderWin = UpgradeWindow.EditControl(AutomationId='txtFileFolder')
    FileFolderWin.SetValue(FileFolder)
    # 输入更新包说明
    PackageRemarkWin = UpgradeWindow.EditControl(AutomationId='txtPackageRemark')
    PackageRemarkWin.SetValue(PackageRemark)
    # 输入账号
    UserWin = UpgradeWindow.EditControl(AutomationId='txtUserId')
    UserWin.SetValue(User)
    # 输入密码
    UserPwWin = UpgradeWindow.EditControl(AutomationId='txtUserPw')
    UserPwWin.SetValue(PassWd)
    # 点击打包并上传
    UploadWin = UpgradeWindow.ButtonControl(AutomationId='btnUpload')
    UploadWin.Click()
    # chose=1048576表示未点击成功，1048577表示点击成功但是弹出已上传提示，1048581表示点击成功，上传中
    chose = UploadWin.AccessibleCurrentState()
    i = 0
    while chose not in (1048577, 1048581):
        i = i + 1
        UploadWin.Click()
        chose = UploadWin.AccessibleCurrentState()
        print(f"{str(chose)},第{str(i)}次重复点击打包并上传按钮")
        if i == 5:
            break

    # 上传成功后的弹窗主界面不一样
    SuccessWindow = automation.WindowControl(searchDepth=1, ClassName='#32770', Name=u'明源更新包上传工具')
    TipsWin = SuccessWindow.TextControl(ClassName='Static')
    MainWin = UpgradeWindow.TextControl(ClassName='Static')
    start = time.time()
    # 先判断失败的弹窗是否出现，失败弹窗会出现得比较快，给1秒判断时间
    if automation.WaitForExist(MainWin, 1):
        TipsWin = UpgradeWindow.TextControl(ClassName='Static')
        TipsText = TipsWin.GetWindowText()
        ConfirmBtn = UpgradeWindow.ButtonControl(AutomationId='2')
        ConfirmBtn.Click()
        # 提示不包含上传成功时,需要检查
        automation.Logger.WriteLine(u"%s！！！！！！【%s】上传【%s】失败,原因: %s！！！！！！！" % (
        time.strftime("%Y-%m-%d %H:%M:%S"), CustomerName, ProductName, TipsText))
    # 判断弹窗的确认按钮是否在200s内出现,如果是上传工作流,等待时间会较长,所以先判断确认弹窗按钮是否存在
    elif automation.WaitForExist(TipsWin, 300):
        # 获取打包并上传后的弹窗提示,用于判断上传是否成功
        TipsWin = SuccessWindow.TextControl(ClassName='Static')
        TipsText = TipsWin.GetWindowText()
        ConfirmBtn = SuccessWindow.ButtonControl(AutomationId='2')
        if u'上传成功' in TipsText:
            # 上传完成后,点击确定
            ConfirmBtn.Click()
            automation.Logger.WriteLine(u"%s:**************【%s】上传【%s】, %s************" % (
            time.strftime("%Y-%m-%d %H:%M:%S"), CustomerName, ProductName, TipsText))
        else:
            # 如果Tips不包含'上传成功'，则应该是失败，获取失败的弹窗，并给出失败提示
            TipsWin = UpgradeWindow.TextControl(ClassName='Static')
            TipsText = TipsWin.GetWindowText()
            ConfirmBtn = UpgradeWindow.ButtonControl(AutomationId='2')
            ConfirmBtn.Click()
            # 提示不包含上传成功时,需要检查
            automation.Logger.WriteLine(u"%s！！！！！！【%s】上传【%s】失败,原因: %s！！！！！！！" % (
            time.strftime("%Y-%m-%d %H:%M:%S"), CustomerName, ProductName, TipsText))
    else:
        automation.Logger.WriteLine(u"%d s超时未出弹窗" % (time.time() - start))


# 定义推包产品及对应文件夹
CoreERP = {
    'productName': '工作流ERP',
    'path': r'E:\09-工作流推包\180511-核心\1.0.1805.1100 对应 核心ERP',
    # 'path':r'E:\09-工作流推包\01更新包推送\03sp1核心-推包\1.0.1805.1100 对应 核心ERP',

}
CoreWF = {
    'productName': '工作流',
    'path': r'E:\09-工作流推包\180511-核心\1.0.1805.1100 工作流',
    # 'path':r'E:\09-工作流推包\01更新包推送\03sp1核心-推包\1.0.1805.1100 工作流'
}
RefactorERP = {
    'productName': '工作流CGERP',
    'path': r'E:\09-工作流推包\180511 -重构-格式\1.0.1805.1100 对应 重构erp站点（使用html表单的）',
}
RefactorWF = {
    'productName': '工作流',
    'path': r'E:\09-工作流推包\180511 -重构-格式\1.0.1805.1100 工作流',
}


# ---------------------------------------------常见的推送集合，推包前设置---------------------------
def CustVer(cust, types):
    dic = {}
    core = [CoreERP, CoreWF]
    refactor = [RefactorERP, RefactorWF]
    integrated = [CoreERP, RefactorERP, RefactorWF]
    corewf = [CoreWF]
    refactorwf = [RefactorWF]
    coreerp = [CoreERP]
    refactorerp = [RefactorERP]
    if types.lower() == 'core':
        dic[cust] = core
    elif types.lower() == 'refactor':
        dic[cust] = refactor
    elif types.lower() == 'integrated':
        dic[cust] = integrated
    elif types.lower() == 'corewf':
        dic[cust] = corewf
    elif types.lower() == 'refactorwf':
        dic[cust] = refactorwf
    elif types.lower() == 'coreerp':
        dic[cust] = coreerp
    elif types.lower() == 'refactorerp':
        dic[cust] = refactorerp
    else:
        print ('输入的集合类型错误')
    # dic.copy()可以不改变原来list的顺序
    return dic.copy()


# -----------------------------------------------------多组客户的数据重组-----------------------------------------------------
# 多组客户推不同版本工作流组合的数据重组
def Custmers(*args):
    # 入参示例：Custmers('吉宝鸿祥管理(上海)有限公司','refactor','重庆新鸥鹏地产（集团）有限公司1','core')
    CustomerVersion = {}
    name, version = [], []
    # 通过奇偶判断进行列表分组
    for i, value in enumerate(args):
        if (i % 2) == 0:
            name.append(value)
        else:
            version.append(value)
    # 通过分组列表进行zip组合成列表，组成{'吉宝鸿祥管理(上海)有限公司':'refactor','重庆新鸥鹏地产（集团）有限公司1':'core'}
    CustVers = dict(zip(name, version))
    # 对列表进行循环执行CustVer函数并update到CustomerVersion，组成最终推包的字典集合---:{"重庆新鸥鹏地产（集团）有限公司1": [{"path": "E:\\09-工作流推包\\180511-核心\\1.0.1805.1100 对应 核心ERP", "productName": "工作流ERP"}, {"path": "E:\\09-工作流推包\\180511-核心\\1.0.1805.1100 工作流", "productName": "工作流"}], "吉宝鸿祥管理(上海)有限公司": [{"path": "E:\\09-工作流推包\\180511 -重构-格式\\1.0.1805.1100 对应 重构erp站点（使用html表单的）", "productName": "工作流CGERP"}, {"path": "E:\\09-工作流推包\\180511 -重构-格式\\1.0.1805.1100 工作流", "productName": "工作流"}]}
    for k, v in CustVers.items():
        CustomerVersion.update(CustVer(k, v))
    # print json.dumps(CustomerVersion, encoding='UTF-8', ensure_ascii=False)
    print (CustomerVersion)
    return CustomerVersion


# -----------------------------------------------------传入参数执行推包-----------------------------------------------------
# 入参示例：
# Custmers('三迪集团','core','重庆新鸥鹏地产（集团）有限公司1','refactor','华熙上旅全域','integrated')
if __name__ == '__main__':
    CustVers = Custmers('河南常绿集团置业有限公司','core')
    # SendUser = {'安徽三巽投资集团有限公司': ['wangg02@mingyuanyun.com']}
    SendUser = {}
    # 给客户对应的项目PM发送邮件，需按照以下格式进行编辑
    # SendUser = {'三迪集团':['123456@789','0001@0002'],'重庆新鸥鹏地产（集团）有限公司1':['123456@789']}
    #  先做一次关闭
    os.system("taskkill /F /IM Mysoft.PackageApp.exe")
    for Cust, ver in CustVers.items():
        global PackageVer
        for product in ver:
            Product = product['productName']
            FileFolder = product['path']
            # global PackageVer
            PackageVer = GetWFVserion(FileFolder)
            PackageName = '【' + PackageVer + '】工作流V2.0自更新包'
            upgradeTools(ToolPath, Cust, Product, PackageName, PackageVer, FileFolder, PackageRemark, User, PassWd)
            os.system("taskkill /F /IM Mysoft.PackageApp.exe")
        # 推包后，发送邮件
        if len(SendUser) != 0:  # 如果发送人是空，则不发送邮件
            for cus, pm_email in SendUser.items():  # 迭代邮件字典，以便有多组推送时，能推送给对应项目的PM
                if cus == Cust:  # 对应的客户，给对应项目PM发送邮件
                    # 默认抄送人，在.\SendEmail.py文件内
                    SendEmail(PackageVer, Cust, pm_email)
                    print ('【' +Cust+ '】推包邮件发送成功，已发送给: ' + ",".join(pm_email))
        print ('-----------------------------------------------------------------------------------')
